package com.hzit.proxy.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzit.net.RedisUtils;
import com.hzit.net.WXNetUtil;
import com.hzit.proxy.base.AccessToken;
import com.sun.org.apache.bcel.internal.generic.RET;

import java.util.List;

public class UserListProxy {


    /**
     * 获取所有的关注用户
     *
     * @return
     */
    public List<String> getUserList(String nextOpenid) {

        String redisKey = "user:list";

        String list = RedisUtils.get(redisKey);

        if (list != null) {
            List<String> strings = JSONArray.parseArray(list, String.class);
            return strings;
        }

        String url = "";
        String token = AccessToken.getToken();
        if (nextOpenid == null) {
            url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token;
        } else {
            url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token + "&next_openid=" + nextOpenid;
        }

        //{
        //    "total":2,
        //    "count":2,
        //    "data":{
        //    "openid":["OPENID1","OPENID2"]},
        //    "next_openid":"NEXT_OPENID"
        //}
        String result = WXNetUtil.get(url);

        //根据条件去获取结果，由weixin接口文档决定
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.containsKey("data")) {
            JSONObject data = jsonObject.getJSONObject("data");

            if (data.containsKey("openid")) {
                JSONArray jsonArray = data.getJSONArray("openid");

                List<String> userList = jsonArray.toJavaList(String.class);

                //放入缓存
                RedisUtils.set(redisKey, jsonArray.toJSONString(), 60 * 10); //有效期十分钟


                return userList;
            }
        }
        return null;
    }
}
